<template>
  <!-- 区域价格管理 -->
  <div>
    <div class="app-page">
      <org-tree
        class="orgTree"
        title="组织机构"
        :tree-data="orgTreeData"
        :mouse-button="false"
        :loading="$loadingPlugin.getTreeData01"
        @currentChange="orgChange"
      />
      <goods-tree
        title="商品分类"
        :tree-data="goodsTypeTreeData"
        :loading="$loadingPlugin.getTreeData02"
        :mouse-button="false"
        @currentChange="goodsTypeChange"
      />
      <lb-table
        ref="lbTable"
        v-el-height-adaptive-table="{bottomOffset:10}"
        class="table"
        border
        highlight-current-row
        element-loading-text="加载中"
        :column="tableData.column"
        :data="tableData.data"
        :pagination="false"
        :immediate-fetch="false"
        @fetch="fetchData"
      />
    </div>
    <set-price ref="setPrice" />
  </div>
</template>

<script>
  import { goodsTypeQueryList, marketPriceDelete, organizationQueryList, queryGoodsListAll, areaPriceAudit } from '@/api'
  import getTreeData from '@/utils/jsonTree'
  import moment from 'dayjs'
  import OrgTree from '@/views/components/OrgTree'
  import GoodsTree from '@/views/components/GoodsTypeTree'
  import SetPrice from './components/SetPrice'

  export default {
    name: 'areaPriceManage',
    components: {
      OrgTree, GoodsTree, SetPrice
    },
    data() {
      return {
        orgTreeData: [],
        goodsTypeTreeData: [],
        currentOrg: null,
        currentGoodsType: null,
        temp: {},
        tableData: {
          total: 0,
          column: [
            {
              prop: 'flag',
              label: '已报价',
              width: 70,
              render: (h, { row }) => {
                // 101 从右往左依次代表呼叫中心、微信、。。。
                if (row.flag) {
                  row.flag = '' + row.flag
                  return <span>{row.flag.charAt(row.flag.length - 1) > 0 && <svg-icon icon-class='phone-green' />}{row.flag.charAt(row.flag.length - 2) > 0 && <svg-icon icon-class='wechat-green' />}</span>
                }
                return ''
              }
            },
            {
              prop: 'status',
              label: '本期报价',
              width: 80,
              render: (h, { row }) => {
                const obj = {
                  '1': '未审核',
                  '2': '已审核',
                  '-1': '已作废'
                }
                const nextStartDt = moment(row.nextStartDt).valueOf()
                if (nextStartDt > new Date('2000-01-01').getTime() && nextStartDt < new Date().getTime() && row.nextPriceStatus === 2) {
                  return <span>{ obj[row.nextPriceStatus] || '未报价' }</span>
                }
                return <span>{ obj[row.status] || '未报价' }</span>
              }
            },
            {
              prop: 'nextPriceStatus',
              label: '下期报价',
              width: 80,
              render: (h, { row }) => {
                const obj = {
                  '1': '未审核',
                  '2': '已审核',
                  '-1': '已作废'
                }
                const nextStartDt = moment(row.nextStartDt).valueOf()
                if (nextStartDt > new Date('2000-01-01').getTime() && nextStartDt < new Date().getTime() && row.nextPriceStatus === 2) {
                  return <span>未报价</span>
                }
                return <span>{ obj[row.nextPriceStatus] || '未报价' }</span>
              }
            },
            {
              prop: 'goodsCode',
              label: '编码',
              width: 70
            },
            {
              prop: 'goodsName',
              label: '名称',
              width: 150
            },
            {
              prop: 'gtName',
              label: '类型',
              width: 100
            },
            {
              prop: 'unitName',
              label: '单位',
              width: 60
            },
            {
              prop: 'remark',
              label: '描述',
              width: 300
            },
            {
              label: '操作',
              align: 'center',
              width: 420,
              render: (h, { row, $index }) => {
                return (
                  <div>
                    <el-link size='mini' underline={false} onClick={() => this.setPrice(row, 'current')}>
                      设置本期报价
                    </el-link>
                    <el-link size='mini' underline={false} type='danger' onClick={() => this.delPrice(row, 0)}>
                      删除本期报价
                    </el-link>
                    <el-link size='mini' underline={false} onClick={() => this.setPrice(row, 'next')}>
                      设置下期报价
                    </el-link>
                    <el-link size='mini' underline={false} type='danger' onClick={() => this.delPrice(row, 1)}>
                      删除下期报价
                    </el-link>
                    <el-link size='mini' underline={false} onClick={() => this.audit(row, $index)}>
                      审核
                    </el-link>
                  </div>
                )
              }
            }
          ],
          data: []
        }
      }
    },
    created() {
      this.getTreeData01()
      this.getTreeData02()
    },
    methods: {
      // 列表查询
      async fetchData() {
        const res = await queryGoodsListAll({
          gtId: this.currentGoodsType.gtId,
          orgSNNo: this.currentOrg.orgSNNo
        })
        this.tableData.data = res.data
      },
      // 设置报价
      setPrice(row, type) {
        if (this.currentOrg.parentId === 0) {
          this.$message.warning('请选择一个机构')
          return
        }
        this.$refs.setPrice.open(row, type)
      },
      // 删除报价
      delPrice(row, index) {
        if (!this.currentOrg || !this.currentOrg.parentId === 0) {
          this.$message.warning('请选择一个机构')
          return
        }
        if (!this.currentGoodsType) {
          this.$message.warning('请选中某一商品')
          return
        }
        if (index === 1) {
          const nextStartDt = moment(row.nextStartDt).valueOf()
          if ((nextStartDt > new Date('2000-01-01').getTime() && nextStartDt < new Date().getTime() && row.nextPriceStatus === 2) || row.nextPriceStatus === 0) {
            this.$message.warning('该商品下期未报价')
            return
          }
        } else {
          if (!row.status && (!row.nextStartDt || moment(row.nextStartDt).valueOf() > new Date().getTime())) {
            this.$message.warning('该商品本期未报价')
            return
          }
        }
        const title = index === 0 ? '本' : '下'
        this.$confirm(`确认要删除该商品的${title}期报价吗？`, '操作提示', {
          type: 'warning'
        }).then(() => {
          const loading = this.$message({
            message: '正在删除',
            duration: 0,
            iconClass: 'el-icon-loading'
          })
          marketPriceDelete({
            orgId: this.currentOrg.orgId,
            goodsId: row.goodsId,
            areaPriceType: 2,
            type: 1, // 0:市场价格,1:区域价格
            next: index // 0:本期,1:下期
          }).then(() => {
            this.$refs.lbTable.fetch()
            this.$notify({
              title: '提示',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          }).finally(() => {
            loading.close()
          })
        })
      },
      // 审核
      audit(row) {
        this.$confirm('确认要审核该商品报价吗？', '操作提示', {
          type: 'warning'
        }).then(() => {
          const loading = this.$message({
            message: '正在审核',
            duration: 0,
            iconClass: 'el-icon-loading'
          })
          areaPriceAudit({
            orgId: this.currentOrg.orgId,
            goodsId: row.goodsId
          }).then(() => {
            this.$refs.lbTable.fetch()
            this.$notify({
              title: '提示',
              message: '审核成功',
              type: 'success',
              duration: 2000
            })
          }).finally(() => {
            loading.close()
          })
        })
      },
      // 获取组织机构数据
      async getTreeData01() {
        const res = await organizationQueryList({})
        const data = res.data.map(item => ({
          label: item.orgName,
          ...item
        }))
        this.orgTreeData = getTreeData(data)
      },
      // 选择组织机构变化
      orgChange(current) {
        this.currentOrg = current
        if (this.currentOrg && this.currentGoodsType) this.fetchData()
      },
      // 获取商品分类树图数据
      async getTreeData02() {
        const res = await goodsTypeQueryList({})
        const data = res.data.map(item => ({
          label: item.gtName,
          ...item
        }))
        this.goodsTypeTreeData = getTreeData(data, 'parentId', 'gtId')
      },
      // 商品分类选择变化
      goodsTypeChange(current) {
        this.currentGoodsType = current
        if (this.currentOrg && this.currentGoodsType) this.fetchData()
      }
    }
  }
</script>

<style lang='scss' scoped>
.app-page {
  display: flex;
  height: calc(100vh - 125px);
  padding: 0;
}
</style>
